package ui;

import com.alee.utils.drag.FileTransferable;
import com.sun.jna.*;
import com.sun.jna.platform.win32.*;
import com.sun.jna.platform.win32.WinDef.*;
import com.sun.jna.platform.win32.WinUser.*;


import service.IFileService;
import service.impl.IFileServiceImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;

public class ContextMenu {
    
	private static IFileService ifileservice=new IFileServiceImpl();
	
    public static void showJavaContextMenu(Component parent,String filepath) {
        JPopupMenu popup = new JPopupMenu();
        File file = new File(filepath);
        
        // 打开菜单项
        JMenuItem openItem = new JMenuItem("打开");
        openItem.addActionListener(e -> openFile(parent, file));
        popup.add(openItem);
        
        // 复制路径菜单项
        JMenuItem copyPathItem = new JMenuItem("复制路径");
        copyPathItem.addActionListener(e -> copyFilePath(parent, file));
        popup.add(copyPathItem);
        
        // 在文件夹中显示菜单项
        JMenuItem showInFolderItem = new JMenuItem("在文件夹中显示");
        showInFolderItem.addActionListener(e -> showInFolder(parent, file));
        popup.add(showInFolderItem);
        
        // 重命名菜单项
        JMenuItem renameItem = new JMenuItem("重命名");
        renameItem.addActionListener(e -> renameFile(parent, file));
        popup.add(renameItem);
        
        // 复制文件菜单项
        JMenuItem copyFileItem = new JMenuItem("复制");
        copyFileItem.addActionListener(e -> copyFileToClipboard(parent, file));
        popup.add(copyFileItem);
        
        // 删除文件菜单项
        JMenuItem deleteFileItem = new JMenuItem("删除");
        deleteFileItem.addActionListener(e -> deleteFile(parent, file));
        popup.add(deleteFileItem);
        
        // 属性菜单项
        JMenuItem propertiesItem = new JMenuItem("属性");
        propertiesItem.addActionListener(e -> showFileProperties(parent, file));
        popup.add(propertiesItem);
        
        // 显示在鼠标位置
        Point p = MouseInfo.getPointerInfo().getLocation();
        SwingUtilities.convertPointFromScreen(p, parent);
        popup.show(parent, p.x, p.y);
    }
    
    private static void openFile(Component parent, File file) {
        try {
            Desktop.getDesktop().open(file);
        } catch (Exception ex) {
            showError(parent, "无法打开文件", ex);
        }
    }
    
    private static void copyFilePath(Component parent, File file) {
        try {
            StringSelection selection = new StringSelection(file.getAbsolutePath());
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
        } catch (Exception ex) {
            showError(parent, "无法复制文件路径", ex);
        }
    }
    
    private static void showInFolder(Component parent, File file) {
        try {
            String cmd = "explorer /select,\"" + file.getAbsolutePath().replace("/", "\\") + "\"";
            Runtime.getRuntime().exec(cmd);
        } catch (Exception ex) {
            showError(parent, "无法在文件夹中显示", ex);
        }
    }
    
    private static void renameFile(Component parent, File file) {
        String newName = JOptionPane.showInputDialog(
            parent,
            "输入新文件名:",
            file.getName());
        
        if (newName != null && !newName.trim().isEmpty()) {
            File newFile = new File(file.getParent(), newName);
            if (file.renameTo(newFile)) {
                JOptionPane.showMessageDialog(
                    parent,
                    "重命名成功",
                    "成功",
                    JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(
                    parent,
                    "重命名失败，请检查文件名是否合法或文件是否被占用",
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private static void copyFile(Component parent, File file) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择复制目标位置");
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        
        int returnValue = fileChooser.showSaveDialog(parent);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File destinationDir = fileChooser.getSelectedFile();
            File destinationFile = new File(destinationDir, file.getName());
            
            try {
                Files.copy(
                    file.toPath(),
                    destinationFile.toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
                JOptionPane.showMessageDialog(
                    parent,
                    "文件复制成功",
                    "成功",
                    JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception ex) {
                showError(parent, "文件复制失败", ex);
            }
        }
    }
    private static void copyFileToClipboard(Component parent, File file) {
        // 获取系统剪贴板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                
        FileTransferable transferable = new FileTransferable(file);       
        // 将文件列表设置到剪贴板
        clipboard.setContents(transferable, null);        
        JOptionPane.showMessageDialog(
            parent,
            "文件已复制到剪贴板!",
            "复制成功",
            JOptionPane.INFORMATION_MESSAGE);
    }
    private static void deleteFile(Component parent, File file) {
        int confirm = JOptionPane.showConfirmDialog(
            parent,
            "确定要删除 '" + file.getName() + "' 吗?",
            "确认删除",
            JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            if (file.delete()) {
                JOptionPane.showMessageDialog(
                    parent,
                    "文件删除成功",
                    "成功",
                    JOptionPane.INFORMATION_MESSAGE);
                //然后删除插件的保存记录
                ifileservice.removeFile(file.getName());
                
            } else {
                JOptionPane.showMessageDialog(
                    parent,
                    "文件删除失败，请检查文件是否被占用",
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    
    private static void showFileProperties(Component parent, File file) {
        try {
            if (!file.exists()) {
                JOptionPane.showMessageDialog(parent, "文件不存在", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (System.getProperty("os.name").toLowerCase().contains("win")) {
                // 方法 1：PowerShell（推荐）
                String cmd = "powershell -command \"$shell = New-Object -ComObject Shell.Application; " +
                             "$shell.Namespace('" + file.getParent().replace("'", "''") + "').ParseName('" + 
                             file.getName().replace("'", "''") + "').InvokeVerb('properties')\"";
                Runtime.getRuntime().exec(cmd);
                
            } else {
                // 非Windows系统的实现（Mac/Linux）
                String message = "文件名: " + file.getName() + "\n" +
                                "路径: " + file.getAbsolutePath() + "\n" +
                                "大小: " + file.length() + " 字节\n" +
                                "最后修改: " + new java.util.Date(file.lastModified());
                
                JOptionPane.showMessageDialog(
                    parent,
                    message,
                    "文件属性",
                    JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (Exception ex) {
            showError(parent, "无法显示文件属性", ex);
        }
    }

    /**
     * 转义 VBScript 中的路径特殊字符（如引号、反斜杠）
     */
    private static String escapeVBSPath(String path) {
        return path.replace("\\", "\\\\").replace("\"", "\\\"");
    }
    
    private static void showError(Component parent, String message, Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(
            parent,
            message + ": " + ex.getMessage(),
            "错误",
            JOptionPane.ERROR_MESSAGE);
    }
}